﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace Creventive.Wpf.ShellFactory.Utility
{
    /// <summary>
    ///   Represents an observable collection which only allow a single instance of any entry.
    /// </summary>
    /// <typeparam name = "T"></typeparam>
    public class ObservableSet<T> : ObservableCollection<T>
    {
        private IEqualityComparer<T> comparer;

        /// <summary>
        ///   Initializes a new instance of the <see cref = "ObservableSet&lt;T&gt;" /> class.
        /// </summary>
        /// <param name = "comparer">The comparer.</param>
        public ObservableSet(IEqualityComparer<T> comparer = null)
        {
            if (comparer == null)
                this.comparer = EqualityComparer<T>.Default;
            else
                this.comparer = comparer;
        }

        /// <summary>
        ///   Inserts the item.
        /// </summary>
        /// <param name = "index">The index.</param>
        /// <param name = "item">The item.</param>
        protected override void InsertItem(int index, T item)
        {
            if (this.Contains(item, this.comparer))
                return;
            base.InsertItem(index, item);
        }

        /// <summary>
        ///   Sets the item.
        /// </summary>
        /// <param name = "index">The index.</param>
        /// <param name = "item">The item.</param>
        protected override void SetItem(int index, T item)
        {
            if (this.Contains(item, this.comparer))
                this.Move(this.IndexOf(item), index);
            else
                base.SetItem(index, item);
        }
    }
}